<?php
/**
 * Character model file.
 *
 * Infectamic: browser game (http://infectamic.goldzoneweb.info)
 * Copyright 2011, Loic Chardonnet
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

App::import('Lib', 'generate_random_name');

/**
 * Class for Character model.
 */
class Character extends AppModel {
    var $name = 'Character';
    var $displayField = 'name';

    var $_schema = array(
	'id' => array(
            'type' => 'integer',
            'length' => 11,
	),
	'name' => array(
            'type' => 'string',
            'length' => 255,
	),
	'resource_points' => array(
            'type' => 'integer',
            'default' => DEFAULT_RESOURCE_POINT,
	),
	'score_points' => array(
            'type' => 'integer',
            'default' => 0,
	),
        'attack_modifier' => array(
            'type' => 'integer',
            'default' => 0,
	),
        'defense_modifier' => array(
            'type' => 'integer',
            'default' => 0,
	),
        'life_modifier' => array(
            'type' => 'integer',
            'default' => 0,
	),
        'created' => array(
            'type' => 'datetime',
	),
    );

    /**
     * Generates randomly a new Character.
     */
    function generateRandomly() {
        $Letter =& ClassRegistry::init('Letter');

        $this->save(array(
            'name' => $Letter->generateRandomName(),
            'resource_points' => $this->_schema['resource_points']['default'],
            'score_points' => $this->_schema['score_points']['default'],
            'attack_modifier' => $this->_schema['attack_modifier']['default'],
            'defense_modifier' => $this->_schema['defense_modifier']['default'],
            'life_modifier' => $this->_schema['life_modifier']['default'],
        ));
    }

    /**
     * Counts the number of characters created in the last 24 hours.
     *
     * @return integer The number of characters.
     */
    function countGeneratedForLastDay() {
        $lastDay = strtotime('-1 day');

        $generated = $this->find('count', array('conditions' => array(
            'Character.created >' => date('Y-m-d H:i:s', $lastDay),
        )));

        return $generated;
    }

    /**
     * Removes the dead characters.
     */
    function removeDeads() {
        $this->deleteAll('UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(Character.created) + Character.resource_points');
    }
}
